package com.tkjt.pms.modules.gm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.tkjt.pms.modules.gm.vo.CommentsVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tkjt.pms.calc.KpiCalculator;
import com.tkjt.pms.calc.common.CalcResult;
import com.tkjt.pms.common.entity.TkIndexValue;
import com.tkjt.pms.common.utils.EsDateUtils;
import com.tkjt.pms.common.vos.TkIndexValueForScoreVO;
import com.tkjt.pms.modules.common.service.TkDataConfigService;
import com.tkjt.pms.modules.common.service.TkIndexValueService;
import com.tkjt.pms.modules.gm.service.TkGmService;
import com.tkjt.pms.modules.gm.vo.TkGmScoresVo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/pms/gm")
public class TkGmController {
	
	//命令与Controller类同： 均以TkGm开头
    @Autowired
    private TkGmService tkGmService;
	@Autowired
	private ISysUserService sysUserService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private KpiCalculator kpiCalculator;
    @Autowired
    private TkDataConfigService tkDataConfigService;
    @Autowired
    private TkIndexValueService tkIndexValueService;

    @Autowired
    private RedisUtil redisUtil;
	
    /**
     ** 评分列表评分项进度
     * @param
     * @return
     */
    @RequestMapping(value = "gmGradedRadio")
    public Result<?> gmGradedRadio(@RequestBody TkIndexValueForScoreVO tkIndexValue){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
        	return Result.error("用户非法！");
        }
        List<String> userRoleCodes = sysUserService.getRole(loginUser.getUsername());
        if(!userRoleCodes.contains("ykkpiowner") && !userRoleCodes.contains("ykgm")) {
        	return Result.error("用户["+loginUser.getUsername()+"]无权限查看数据！");
        }
        try {
            return Result.ok(tkGmService.gmGradedRadio(loginUser,tkIndexValue.getIndexYearMonth()));
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("获取数据异常");
        }
    }

    /**
     **评分列表
     * @param
     * @return
     */
    @RequestMapping(value = "gmDatagrid")
    public Result<?> gmDatagrid(@RequestBody TkIndexValueForScoreVO tkIndexValue){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        List<String> userRoleCodes = sysUserService.getRole(loginUser.getUsername());
        if(!userRoleCodes.contains("ykkpiowner") && !userRoleCodes.contains("ykgm")) {
            return Result.error("用户["+loginUser.getUsername()+"]无权限查看数据！");
        }
        return tkGmService.gmDatagrid(loginUser,tkIndexValue,tkIndexValue.getPageNo(),tkIndexValue.getPageSize());
    }
    /**
     ** 评分参考(双向评分记录列表)
     * @param
     * @return
     */
    @RequestMapping(value = "cgDatagrid")
    public Result<?> cgDatagrid(@RequestBody TkIndexValueForScoreVO tkIndexValue,HttpServletRequest req){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        try {
            return Result.ok(tkGmService.doubleDatagrid(loginUser,tkIndexValue,tkIndexValue.getPageNo(),tkIndexValue.getPageSize()));
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("获取数据异常");
        }

    }
    /**
     **双向评分记录列表(从总经理评分页面跳转)
     * @param
     * @return
     */
    @RequestMapping(value = "cgGmDatagrid")
    public Result<?> cgGmDatagrid(@RequestBody TkIndexValueForScoreVO tkIndexValue,HttpServletRequest req){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        String indexDepart = tkIndexValue.getIndexDepart();
        if(indexDepart == null || "".equals(indexDepart)){
            return Result.error("参数缺失");
        }
        String indexScorer = tkIndexValue.getIndexScorer();
        if(indexScorer == null || "".equals(indexScorer)){
            return Result.error("参数缺失");
        }
        String indexValueCode = tkIndexValue.getIndexValueCode();
        if(indexValueCode == null || "".equals(indexValueCode)){
            return Result.error("参数缺失");
        }
        SysUser user = sysUserService.getUserByName(indexScorer);
        QueryWrapper<SysDepart> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.lambda().eq(SysDepart::getOrgCode,tkIndexValue.getIndexDepart());
        SysDepart sysDepart = sysDepartService.getOne(objectQueryWrapper);
        try {
            Map<String,Object> pageMap = tkGmService.cgDatagrid(loginUser,tkIndexValue,tkIndexValue.getPageNo(),tkIndexValue.getPageSize());
            pageMap.put("indexYearMonth",tkIndexValue.getIndexYearMonth());
            pageMap.put("indexDepartName",sysDepart != null ? sysDepart.getDepartName() : null);
            pageMap.put("indexDepart",tkIndexValue.getIndexDepart());
            pageMap.put("indexScorerName",user != null ? user.getRealname() : null);
            pageMap.put("indexScorer",tkIndexValue.getIndexScorer());
            return Result.ok(pageMap);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("获取数据异常");
        }
    }
    /**
     ** 绩效得分记录
     * @param
     * @return
     */
    @RequestMapping(value = "scoreDatagrid")
    public Result<?> scoreDatagrid(@RequestBody TkIndexValueForScoreVO tkIndexValue,HttpServletRequest req){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }

        try {
            return tkGmService.scoreDatagrid(loginUser,tkIndexValue,tkIndexValue.getPageNo(),tkIndexValue.getPageSize());
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("获取数据异常");
        }
    }

    /**
     ** 绩效得分记录(从总经理评分页面跳转)
     * @param
     * @return
     */
    @RequestMapping(value = "scoreGmDatagrid")
    public Result<?> scoreGmDatagrid(@RequestBody TkIndexValueForScoreVO tkIndexValue,HttpServletRequest req){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        try {
            return tkGmService.scoreGmDatagrid(loginUser,tkIndexValue);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("获取数据异常");
        }
    }

    /**
     ** 总经理评分保存
     * @param
     * @return
     */
    @RequestMapping(value = "saveScores", method = RequestMethod.POST)
    public Result<?> saveScores(@RequestBody TkGmScoresVo tkGmScoresVo){
    	
    	List<TkIndexValueForScoreVO> vos = tkGmScoresVo.getTkIndexValueVOs();
    	if(CollectionUtils.isEmpty(vos)) {
    		return Result.ok();
    	}
    	
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        String yearMonth = tkGmScoresVo.getIndexYearMonth();
        if(StringUtils.isEmpty(yearMonth)) {
        	yearMonth = EsDateUtils.getIndexYearMonth(new Date());
        }
        
        //保存总经理评分和评分意见
        Result<?> result = tkGmService.saveScores(loginUser, yearMonth, vos);
        String redisKey = loginUser.getUsername()+"@"+loginUser.getOrgCode()+"@"+yearMonth;
        @SuppressWarnings("unchecked")
		List<Map<String,Object>> saveDataList = (List<Map<String,Object>>)redisUtil.get(redisKey);
        if(null == saveDataList) {
        	saveDataList = new ArrayList<>();
        }
        //redisUtil.del(redisKey);
        //List<Map<String,Object>> saveDataList = new ArrayList<>();
        for(TkIndexValueForScoreVO indexValueForScoreVO : vos){
            QueryWrapper<TkIndexValue> indexValueQuery = new QueryWrapper<>();
            indexValueQuery.lambda().eq(TkIndexValue::getId,indexValueForScoreVO.getId());
            TkIndexValue tkIndexValue = tkIndexValueService.getOne(indexValueQuery);
            String indexValueCode = tkIndexValue.getIndexValueCode();
            String indexDepart = tkIndexValue.getIndexDepart();
            String indexGroup = "A01A01A01".equals(indexDepart.substring(0,9)) ? "C" : "G";
            Map<String,Object> saveData = new HashMap<>();
            saveData.put("indexValueCode",indexValueCode);
            saveData.put("indexDepart",indexDepart);
            saveData.put("indexGroup",indexGroup);
            saveDataList.add(saveData);
        }
        redisUtil.set(redisKey,saveDataList);
        return result;
    }
   
    @RequestMapping(value = "calcScores", method = RequestMethod.POST)
    public Result<?> calcScores(@RequestBody TkGmScoresVo tkGmScoresVo){
    	
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
    	
        String yearMonth = tkGmScoresVo.getIndexYearMonth();
        if(StringUtils.isEmpty(yearMonth)) {
            yearMonth = EsDateUtils.getIndexYearMonth(new Date());
        }
        
        //保存总经理评分和评分意见
        try {
        	List<TkIndexValueForScoreVO> vos = tkGmScoresVo.getTkIndexValueVOs();
        	if(!CollectionUtils.isEmpty(vos)) {
                Result<?> result = tkGmService.saveScores(loginUser, yearMonth, vos);
                if(result.getCode() != 200){
                    return result;
                }
                String redisKey = loginUser.getUsername()+"@"+loginUser.getOrgCode()+"@"+yearMonth;
                @SuppressWarnings("unchecked")
    			List<Map<String,Object>> saveDataList = (List<Map<String,Object>>)redisUtil.get(redisKey);
                if(null == saveDataList) {
                	saveDataList = new ArrayList<>();
                }
                for(TkIndexValueForScoreVO indexValueForScoreVO : vos){
                    QueryWrapper<TkIndexValue> indexValueQuery = new QueryWrapper<>();
                    indexValueQuery.lambda().eq(TkIndexValue::getId,indexValueForScoreVO.getId());
                    TkIndexValue tkIndexValue = tkIndexValueService.getOne(indexValueQuery);
                    String indexValueCode = tkIndexValue.getIndexValueCode();
                    String indexDepart = tkIndexValue.getIndexDepart();
                    String indexGroup = "A01A01A01".equals(indexDepart.substring(0,9)) ? "C" : "G";
                    Map<String,Object> saveData = new HashMap<>();
                    saveData.put("indexValueCode",indexValueCode);
                    saveData.put("indexDepart",indexDepart);
                    saveData.put("indexGroup",indexGroup);
                    saveDataList.add(saveData);
                }
                redisUtil.set(redisKey,saveDataList);
        	}
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return Result.error("获取数据异常");
        }
        try {
            log.info("kaGradeCalc, start....");
            //计算绩效分数
            String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
            String indexYearMonth = tkGmScoresVo.getIndexYearMonth();
            String redisKey = loginUser.getUsername()+"@"+loginUser.getOrgCode()+"@"+yearMonth;
            @SuppressWarnings("unchecked")
			List<Map<String,Object>> saveDataList = (List<Map<String,Object>>)redisUtil.get(redisKey);
            if(saveDataList != null && saveDataList.size() > 0){
                for(Map<String,Object> saveData : saveDataList) {
                    String indexValueCode = saveData.get("indexValueCode").toString();
                    String indexDepart = saveData.get("indexDepart").toString();
                    String indexGroup = saveData.get("indexGroup").toString();
                    CalcResult<String> calcResult = kpiCalculator.doCalculatorDirectly(dataType, indexYearMonth, indexGroup, indexValueCode, indexDepart);
                    if(!calcResult.isSuccess()) {
                    	return Result.error(calcResult.getMessage());
                    }
                }
                redisUtil.set(redisKey, new ArrayList<Map<String,Object>>());
            }
            log.info("kaGradeCalc, end.");
            return Result.ok();
        }catch (Exception e){e.printStackTrace();
            return Result.error("得分计算异常！");
        }
    }
    @RequestMapping(value = "getCommentsReport", method = RequestMethod.POST)
    public Result<?> getCommentsReport(@RequestBody CommentsVo commentsVo){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return tkGmService.getCommentsReport(loginUser,commentsVo);
    }
}
